package com.example.cyberqueueandroid;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.AsyncTask;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;

public class PositionsManager {
	private CookieManager mCookieManager = null;
	private String mQueue = null;

	public PositionsManager(WebView wv) {
		CookieSyncManager syncManager = CookieSyncManager.createInstance(wv.getContext());
		syncManager.sync();
		mCookieManager = CookieManager.getInstance();
	}

	private ArrayList<String> getQueueCookie() {
		mCookieManager.removeExpiredCookie();
		String cockie = mCookieManager.getCookie(SharedData.HOSTNAME);
		return Utils.splitQueuesCockie(cockie);
	}

	private String getUserName() {
		List<String> cookies = getQueueCookie();
		for (String c : cookies) {
			String userName = Utils.getUserFromCockie(c);
			if (userName != null) {
				return userName;
			}
		}
		return null;
	}

	private int getPositionNumber(final String pos) {
		AsyncTask<Void, Void, Integer> task = new AsyncTask<Void, Void, Integer>() {
			@Override
			protected Integer doInBackground(Void... arg0) {
				HttpClient httpclient = new DefaultHttpClient();
				String requestURI = SharedData.URI + "/get_position?pos_id=" + pos;
				try {
					HttpResponse response = httpclient.execute(new HttpGet(requestURI));
					StatusLine statusLine = response.getStatusLine();
					if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						response.getEntity().writeTo(out);
						out.close();
						String s = out.toString().trim();
						Integer pos = Integer.valueOf(s);
						return pos;
					}
				} catch (ClientProtocolException e) {
				} catch (IOException e) {
				}
				return -2;
			}
		};
		task.execute();
		try {
			return task.get();
		} catch (InterruptedException e) {
			return -2;
		} catch (ExecutionException e) {
			return -2;
		}
	}

	private List<String> getPositions(final String user_id) {
		AsyncTask<Void, Void, List<String>> task = new AsyncTask<Void, Void, List<String>>() {
			@Override
			protected List<String> doInBackground(Void... arg0) {
				HttpClient httpclient = new DefaultHttpClient();
				String requestURI = SharedData.URI + "/get_all_positions?user_id=" + user_id;
				try {
					HttpResponse response = httpclient.execute(new HttpGet(requestURI));
					StatusLine statusLine = response.getStatusLine();
					if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						response.getEntity().writeTo(out);
						out.close();

						String[] lines = out.toString().split("\\n");
						return Arrays.asList(lines);
					}
				} catch (ClientProtocolException e) {
				} catch (IOException e) {
				}
				return null;
			}
		};
		task.execute();
		try {
			return task.get();
		} catch (InterruptedException e) {
			return null;
		} catch (ExecutionException e) {
			return null;
		}
	}

	private String getQueue(final String pos) {
		AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
			@Override
			protected String doInBackground(Void... arg0) {
				HttpClient httpclient = new DefaultHttpClient();
				String requestURI = SharedData.URI + "/pos_queue?pos_id=" + pos;
				try {
					HttpResponse response = httpclient.execute(new HttpGet(requestURI));
					StatusLine statusLine = response.getStatusLine();
					if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
						ByteArrayOutputStream out = new ByteArrayOutputStream();
						response.getEntity().writeTo(out);
						out.close();
						return out.toString();
					}
				} catch (ClientProtocolException e) {
				} catch (IOException e) {
				}
				return null;
			}
		};
		task.execute();
		try {
			return task.get();
		} catch (InterruptedException e) {
			return null;
		} catch (ExecutionException e) {
			return null;
		}
	}

	public int getUserPosition() {
		String username = getUserName();
		if (username == null) {
			return -2;
		}
		List<String> positions = getPositions(username);
		if (positions == null) {
			return -2;
		}
		for (String pos : positions) {
			int posNum = getPositionNumber(pos);
			if (posNum >= 0) {
				mQueue = getQueue(pos);
				return posNum;
			}
		}
		mQueue = null;
		return -2;
	}

	public String getQueueID() {
		return mQueue;
	}
}
